// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境

const db = cloud.database();
// 云函数入口函数
exports.main = async (event, context) => {
  // 用户默认头像
  let userImg = 'cloud://cloud1-8gadpdagd5a475a3.636c-cloud1-8gadpdagd5a475a3-1315985777/userimg/ad4f0f57310f429092bde1ee72809173.jpg';
  // 用户默认简介
  let desc = 'hahaha';
  // 随机生成昵称
  let nickname = 'cer' + new Date().getTime();

  // 注册时间
  let t = new Date();
  let year = t.getFullYear();
  let month = t.getMonth() + 1;
  month = month >= 10 ? month : `0${month}`;
  let date = t.getDate();
  date = date >= 10 ? date : `0${date}`;
  let hours = t.getHours();
  hours = hours >= 10 ? hours : `0${hours}`;
  let minutes = t.getMinutes();
  minutes = minutes >= 10 ? minutes : `0${minutes}`;
  let seconds = t.getSeconds();
  seconds = seconds >= 10 ? seconds : `0${seconds}`;
  let registerTime = `${year}-${month}-${date} ${hours}:${minutes}:${seconds}`;

   await db.collection('user').add({
    data:{
      userImg,
      desc,
      nickname,
      phone:event.phone,
      password:event.password,
      registerTime
    }
  })
  // 自动登录,将登录状态保存在数据库中(login_user)
  let current = await db.collection('login_status').add({
    data:{
      phone:event.phone,
      // 登录状态
      loginStatus:true
    }
  })
  // console.log("current=>",current);
  return{
    msg:'登录成功',
    code:1,
    _id:current._id
  }
}